package cn.spream.jstudy.mongodb.dao.user.impl;

import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import cn.spream.jstudy.mongodb.dao.user.UserDao;
import cn.spream.jstudy.mongodb.domain.user.User;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: sjx
 * Date: 14-8-15
 * Time: 下午3:32
 * To change this template use File | Settings | File Templates.
 */
public class UserDaoMongoTemplateImpl implements UserDao {

    private MongoTemplate mongoTemplate;

    @Override
    public int add(User user) {
        mongoTemplate.insert(user);
        return 1;
    }

    @Override
    public int delete(User user) {
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(user.getId()));
        mongoTemplate.remove(query, User.class);
        return 1;
    }

    @Override
    public int update(User user) {
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(user.getId()));
        Update update = new Update();
        update.set("name", user.getName());
        update.set("sex", user.getSex());
        update.set("age", user.getAge());
        update.set("address", user.getAddress());
        update.set("mobile", user.getMobile());
        return mongoTemplate.updateFirst(query, update, User.class).getN();
    }

    @Override
    public User getById(String id) {
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(id));
        return mongoTemplate.findOne(query, User.class);
    }

    @Override
    public List<User> find() {
        return mongoTemplate.findAll(User.class);
    }

    public MongoTemplate getMongoTemplate() {
        return mongoTemplate;
    }

    public void setMongoTemplate(MongoTemplate mongoTemplate) {
        this.mongoTemplate = mongoTemplate;
    }
}
